local skynet = require "skynet"
local socket = require "skynet.socket"
--sproto
local sprotoloader = require "sprotoloader"
local host = sprotoloader.load(1):host "package"
local request = host:attach(sprotoloader.load(2))

--
local Agent = {}
local clientFd = nil


-----------------------------------------------------------
--sproto消息分发
-----------------------------------------------------------
--根据收到的消息解出名字
function Agent:CallFunction(t, name, args, player)
    local f = self[name]
    if f then
        f(self, args, player)
    end
end

-----------------------------------------------------------
--通用函数
-----------------------------------------------------------
local function SocketWrite(fd, pack)
    local package = string.pack(">s2", pack)
    assert(fd~=0, "---->socket closed!")
	socket.write(fd, pack)
end

--发送消息至某个客户端
local function SendDataInLua(sendAddr, msg)    
    --local msgSend = string.pack('>I2>I2', MainCmdId, SubCmdId)
    local msgSend = ''
    if msg then
    	--msgSend = msgSend..msg 
    end
    SocketWrite(sendAddr, msg)
end

--客户端消息接收
 local function OnGameMsg(msg, sz, player)
    --local s = string.unpack("c"..string.len(msg)-4, msg, 5)
    local t, name, args = host:dispatch(msg)
    Agent:CallFunction(t, name, args, player)
end

--打印数据的二进制
local function PrintBin(s)
    s=string.gsub(s,"(.)",function (x) return string.format("%02X ",string.byte(x)) end)
    return s
end


-----------------------------------------------------------
--agent主逻辑
-----------------------------------------------------------
function Agent.Start(conf)
	skynet.error("Agent Start! [fd]--->", conf.client)
	local fd = conf.client
	local gate = conf.gate
	WATCHDOG = conf.watchdog

	clientFd = fd
	skynet.call(gate, "lua", "forward", fd)
end

function Agent:Login(args, player)
	skynet.error("Have an agent Login!  args---->", args.token)
	local loginOk = {
		iRet = 1,
	}
	SendDataInLua(clientFd, request("LoginOK", loginOk))
end


-----------------------------------------------------------
--入口 
-----------------------------------------------------------
skynet.register_protocol {
	name = "client",
	id = skynet.PTYPE_CLIENT,
	unpack = function (msg, sz)
		return skynet.tostring(msg, sz)
	end,
	dispatch = function (_, _, msg, sz)
		local ok, result  = pcall(OnGameMsg, msg, sz)
	end
}

skynet.start(function()
	skynet.dispatch("lua", function(_,_, command, ...)
		local f = Agent[command]
		assert(command~=nil, "Command==nil !")
		assert(f~=nil, "[Command]---->"..command)
		skynet.ret(skynet.pack(f(...)))
	end)
end)


